package com.ccg.plat.presentation.ui.feature6.view

import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.VideoSize
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ScreenUtils
import com.ccg.plat.R
import com.ccg.plat.data.local.cache.UserInfoCache
import com.ccg.plat.presentation.ui.feature4.model.VideoBean
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import timber.log.Timber

/**
 * @author : C4_雍和
 * 描述 : 视频播放器页面，支持收藏功能和视频尺寸监听
 * 主要功能 :
 * - 使用Media3 ExoPlayer播放视频
 * - 支持视频收藏/取消收藏
 * - 自动隐藏收藏按钮
 * - 监听视频尺寸变化
 * 维护人员 : C4_雍和
 * date : 2025/8/9 8:54
 */
class VideoPlayerActivity : AppCompatActivity() {

    companion object {
        const val EXTRA_VIDEO_JSON = "json"
        private const val COLLECT_KEY = "collect"
        private const val BUTTON_HIDE_DELAY = 4000L
    }

    private val context = this
    private lateinit var playerView: PlayerView
    private lateinit var collectButton: Button
    private lateinit var switchButton: Button
    private lateinit var llSkin: LinearLayout
    private lateinit var exoPlayer: ExoPlayer

    private val collectListData = mutableListOf<VideoBean>()
    private var currentVideoData: VideoBean? = null
    private val gson = Gson()
    private val mmkv = MMKV.defaultMMKV()

    private var hideButtonJob: Job? = null
    private var videoPlayerHeight = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Timber.e("1111111111111")
        setupView()
        initializeViews()
        initializePlayer()
        loadVideoData()
        loadCollectData()
        setupListeners()
        showCollectButton()
    }

    /**
     * 设置视图和系统UI
     */
    private fun setupView() {
        enableEdgeToEdge()
        setContentView(R.layout.activity_video_player)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            view.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 根据缓存状态设置初始屏幕方向
        if (UserInfoCache.isPagerState()) {
            ScreenUtils.setLandscape(this)
        } else {
            ScreenUtils.setPortrait(this)
        }
    }

    /**
     * 初始化视图组件
     */
    private fun initializeViews() {
        playerView = findViewById(R.id.player_view)
        collectButton = findViewById(R.id.btn_collect)
        switchButton = findViewById(R.id.btn_switch)
        llSkin = findViewById(R.id.ll_skin)
    }


    /**
     * 初始化播放器
     */
    private fun initializePlayer() {
        exoPlayer = ExoPlayer.Builder(this).build()
        playerView.player = exoPlayer

        // 添加播放器监听器
        exoPlayer.addListener(object : Player.Listener {
            override fun onVideoSizeChanged(videoSize: VideoSize) {
                super.onVideoSizeChanged(videoSize)
                handleVideoSizeChanged(videoSize)
            }

            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)
                when (playbackState) {
                    Player.STATE_READY -> {
                        Timber.e("播放器准备完成")
                        logCurrentVideoSize()
                    }
                    Player.STATE_ENDED -> {
                        Timber.e("视频播放完成")
                    }
                    Player.STATE_BUFFERING -> {
                        Timber.e("视频缓冲中...")
                    }
                }
            }

            override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
                super.onPlayerError(error)
                Timber.e("播放错误: ${error.message}")
                Toast.makeText(this@VideoPlayerActivity, "视频播放错误", Toast.LENGTH_SHORT).show()
            }
        })
    }

    /**
     * 加载视频数据
     */
    private fun loadVideoData() {
        intent.getStringExtra(EXTRA_VIDEO_JSON)?.let { jsonString ->
            try {
                currentVideoData = gson.fromJson(jsonString, VideoBean::class.java)
                currentVideoData?.let { videoData ->
                    playVideo(videoData)
                } ?: run {
                    Timber.e("视频数据解析失败")
                    finish()
                }
            } catch (e: Exception) {
                Timber.e("解析视频数据异常")
                Toast.makeText(this, "视频数据错误", Toast.LENGTH_SHORT).show()
                finish()
            }
        } ?: run {
            Timber.e("未提供视频数据")
            finish()
        }
    }

    /**
     * 播放视频
     */
    private fun playVideo(videoData: VideoBean) {
        try {
            val mediaItem = MediaItem.fromUri(videoData.vUrl)
            exoPlayer.setMediaItem(mediaItem)
            exoPlayer.prepare()
            exoPlayer.play()

            Timber.e("开始播放视频: ${videoData.name}")
        } catch (e: Exception) {
            Timber.e("播放视频失败")
            Toast.makeText(this, "播放失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 加载收藏数据
     */
    private fun loadCollectData() {
        try {
            val collectJson = mmkv.decodeString(COLLECT_KEY, "") ?: ""
            collectListData.clear()

            if (collectJson.isNotEmpty()) {
                val listType = object : TypeToken<List<VideoBean>>() {}.type
                val loadedList = gson.fromJson<List<VideoBean>>(collectJson, listType)
                collectListData.addAll(loadedList)
            }

            updateCollectButtonText()
            Timber.e("收藏列表加载完成，共${collectListData.size}个视频")
        } catch (e: Exception) {
            Timber.e("加载收藏数据失败")
        }
    }

    /**
     * 更新收藏按钮文本
     */
    private fun updateCollectButtonText() {
        currentVideoData?.let { videoData ->
            collectButton.text = if (collectListData.contains(videoData)) {
                "删除收藏"
            } else {
                "收藏"
            }
        }
    }

    /**
     * 设置监听器
     */
    private fun setupListeners() {
        // 播放器点击事件
        playerView.setOnClickListener {
            showCollectButton()
        }

        // 收藏按钮点击事件
        collectButton.setOnClickListener {
            handleCollectButtonClick()
        }

        // 横竖屏切换按钮点击事件
        switchButton.setOnClickListener {
            when (resources.configuration.orientation) {
                Configuration.ORIENTATION_PORTRAIT -> {
                    ScreenUtils.setLandscape(context)
                }
                Configuration.ORIENTATION_LANDSCAPE -> {
                    ScreenUtils.setPortrait(context)
                }
            }
        }
    }

    /**
     * 处理收藏按钮点击
     */
    private fun handleCollectButtonClick() {
        currentVideoData?.let { videoData ->
            if (collectListData.contains(videoData)) {
                // 取消收藏
                collectListData.remove(videoData)
                collectButton.text = "收藏"
                Toast.makeText(this, "已从收藏夹中删除", Toast.LENGTH_SHORT).show()
                Timber.e("取消收藏: ${videoData.name}")
            } else {
                // 添加收藏
                collectListData.add(videoData)
                collectButton.text = "删除收藏"
                Toast.makeText(this, "已添加到收藏夹", Toast.LENGTH_SHORT).show()
                Timber.e("添加收藏: ${videoData.name}")
            }

            saveCollectData()
        }
    }

    /**
     * 保存收藏数据
     */
    private fun saveCollectData() {
        try {
            val collectJson = if (collectListData.isNotEmpty()) {
                gson.toJson(collectListData)
            } else {
                ""
            }
            mmkv.encode(COLLECT_KEY, collectJson)
            Timber.e("收藏数据已保存")
        } catch (e: Exception) {
            Timber.e("保存收藏数据失败")
        }
    }

    /**
     * 显示收藏按钮并在指定时间后隐藏
     */
    private fun showCollectButton() {
        // 取消之前的隐藏任务
        hideButtonJob?.cancel()

        llSkin.visibility = View.VISIBLE

        // 启动新的隐藏任务
        hideButtonJob = lifecycleScope.launch {
            delay(BUTTON_HIDE_DELAY)
            if (isActive) {
                llSkin.visibility = View.GONE
            }
        }
    }

    /**
     * 处理视频尺寸变化
     */
    private fun handleVideoSizeChanged(videoSize: VideoSize) {
        val videoWidth = videoSize.width
        val videoHeight = videoSize.height

        if (videoWidth > 0 && videoHeight > 0) {
            val screenWidth = ScreenUtils.getScreenWidth()
            videoPlayerHeight = screenWidth * videoHeight / videoWidth
        }

        updateVideoSize()
    }

    /**
     * 更新视频尺寸
     */
    private fun updateVideoSize() {
        when (resources.configuration.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> {
                setPortraitVideoSize()
            }
            Configuration.ORIENTATION_LANDSCAPE -> {
                setLandscapeVideoSize()
            }
        }
    }

    /**
     * 设置竖屏视频尺寸
     */
    private fun setPortraitVideoSize() {
        val params = playerView.layoutParams
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        params.height = if (videoPlayerHeight > 0) videoPlayerHeight else ViewGroup.LayoutParams.WRAP_CONTENT
        playerView.layoutParams = params
    }

    /**
     * 设置横屏视频尺寸
     */
    private fun setLandscapeVideoSize() {
        val params = playerView.layoutParams
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        params.height = ViewGroup.LayoutParams.MATCH_PARENT
        playerView.layoutParams = params
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)

        when (newConfig.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> {
                // 竖屏：显示状态栏和导航栏
                BarUtils.setStatusBarVisibility(this, true)
                BarUtils.setNavBarVisibility(this, true)
                setPortraitVideoSize()
            }
            Configuration.ORIENTATION_LANDSCAPE -> {
                // 横屏：隐藏状态栏和导航栏
                BarUtils.setStatusBarVisibility(this, false)
                BarUtils.setNavBarVisibility(this, false)
                setLandscapeVideoSize()
            }
        }
    }

    /**
     * 获取当前视频尺寸
     */
    private fun getCurrentVideoSize(): VideoSize? {
        return if (::exoPlayer.isInitialized) {
            val videoSize = exoPlayer.videoSize
            if (videoSize.width > 0 && videoSize.height > 0) {
                videoSize
            } else {
                null
            }
        } else {
            null
        }
    }

    /**
     * 记录当前视频尺寸
     */
    private fun logCurrentVideoSize() {
        getCurrentVideoSize()?.let { videoSize ->
            Timber.e("当前视频尺寸: ${videoSize.width}x${videoSize.height}")
        } ?: run {
            Timber.e("视频尺寸暂未获取到")
        }
    }

    override fun onPause() {
        super.onPause()
        exoPlayer.pause()
    }

    override fun onResume() {
        super.onResume()
        if (exoPlayer.playbackState == Player.STATE_READY) {
            exoPlayer.play()
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        // 取消协程任务
        hideButtonJob?.cancel()

        // 释放播放器资源
        if (::exoPlayer.isInitialized) {
            try {
                exoPlayer.release()
                Timber.e("播放器资源已释放")
            } catch (e: Exception) {
                Timber.e("释放播放器资源时出错")
            }
        }
    }
}